package com.ling.recipeassistant.ui.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.ling.recipeassistant.data.model.Recipe
import com.ling.recipeassistant.data.repository.RecipeRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class HomeViewModel @Inject constructor(
    private val recipeRepository: RecipeRepository
) : ViewModel() {
    
    private val _uiState = MutableStateFlow(HomeUiState())
    val uiState: StateFlow<HomeUiState> = _uiState.asStateFlow()
    
    // 分页相关参数
    private val pageSize = 10
    private var currentPage = 0
    private var allRecipes = listOf<Recipe>()
    private var hasMoreData = true
    
    init {
        loadRecommendedRecipes()
        loadCategories()
        loadAllRecipes()
    }
    
    fun loadRecommendedRecipes() {
        viewModelScope.launch {
            _uiState.value = _uiState.value.copy(isLoadingRecommended = true)
            try {
                // 从数据库获取高评分菜谱作为推荐
                recipeRepository.getTopRatedRecipes(5).collectLatest { recipes ->
                    _uiState.value = _uiState.value.copy(
                        recommendedRecipes = recipes,
                        isLoadingRecommended = false
                    )
                }
            } catch (e: Exception) {
                _uiState.value = _uiState.value.copy(
                    error = e.message ?: "加载推荐菜谱失败",
                    isLoadingRecommended = false
                )
            }
        }
    }
    
    fun loadCategories() {
        viewModelScope.launch {
            try {
                recipeRepository.getAllCategories().collectLatest { categories ->
                    _uiState.value = _uiState.value.copy(categories = categories)
                }
            } catch (e: Exception) {
                // 如果获取分类失败，使用默认分类
                val defaultCategories = listOf(
                    "家常菜", "川菜", "粤菜", "西餐", "甜点", "汤类", "素食", "早餐", "饮品"
                )
                _uiState.value = _uiState.value.copy(categories = defaultCategories)
            }
        }
    }
    
    fun loadAllRecipes() {
        viewModelScope.launch {
            _uiState.value = _uiState.value.copy(isLoadingAll = true)
            try {
                // 从数据库获取所有菜谱
                recipeRepository.getAllRecipes().collectLatest { recipes ->
                    allRecipes = recipes.shuffled()
                    currentPage = 0
                    hasMoreData = allRecipes.isNotEmpty()
                    
                    // 加载第一页
                    loadNextPage()
                }
            } catch (e: Exception) {
                _uiState.value = _uiState.value.copy(
                    error = e.message ?: "加载菜谱失败",
                    isLoadingAll = false
                )
            }
        }
    }
    
    fun loadNextPage() {
        if (!hasMoreData || _uiState.value.isLoadingMore) return
        
        viewModelScope.launch {
            _uiState.value = _uiState.value.copy(isLoadingMore = true)
            try {
                val startIndex = currentPage * pageSize
                val endIndex = minOf(startIndex + pageSize, allRecipes.size)
                
                if (startIndex < allRecipes.size) {
                    val newRecipes = allRecipes.subList(startIndex, endIndex)
                    val currentRecipes = _uiState.value.allRecipes.toMutableList()
                    currentRecipes.addAll(newRecipes)
                    
                    currentPage++
                    hasMoreData = endIndex < allRecipes.size
                    
                    _uiState.value = _uiState.value.copy(
                        allRecipes = currentRecipes,
                        isLoadingMore = false,
                        isLoadingAll = false,
                        hasMoreData = hasMoreData
                    )
                } else {
                    hasMoreData = false
                    _uiState.value = _uiState.value.copy(
                        isLoadingMore = false,
                        isLoadingAll = false,
                        hasMoreData = false
                    )
                }
            } catch (e: Exception) {
                _uiState.value = _uiState.value.copy(
                    error = e.message ?: "加载更多菜谱失败",
                    isLoadingMore = false,
                    isLoadingAll = false
                )
            }
        }
    }
    
    fun refreshData() {
        currentPage = 0
        hasMoreData = true
        _uiState.value = _uiState.value.copy(
            allRecipes = emptyList(),
            hasMoreData = true
        )
        loadAllRecipes()
    }
    
    fun onCategoryClick(category: String) {
        viewModelScope.launch {
            _uiState.value = _uiState.value.copy(isLoadingAll = true)
            try {
                // 根据分类筛选菜谱
                recipeRepository.getRecipesByCategory(category).collectLatest { recipes ->
                    allRecipes = recipes.shuffled()
                    currentPage = 0
                    hasMoreData = allRecipes.isNotEmpty()
                    
                    // 重置并加载第一页
                    _uiState.value = _uiState.value.copy(
                        allRecipes = emptyList(),
                        hasMoreData = hasMoreData
                    )
                    loadNextPage()
                }
            } catch (e: Exception) {
                _uiState.value = _uiState.value.copy(
                    error = e.message ?: "筛选菜谱失败",
                    isLoadingAll = false
                )
            }
        }
    }
    
    fun onRecipeClick(recipe: Recipe) {
        // 处理菜谱点击事件
    }
    
    // 收藏功能
    fun toggleFavorite(recipeId: String) {
        viewModelScope.launch {
            try {
                recipeRepository.toggleFavorite(recipeId)
                // 重新加载数据以更新收藏状态
                loadRecommendedRecipes()
                loadAllRecipes()
            } catch (e: Exception) {
                _uiState.value = _uiState.value.copy(
                    error = e.message ?: "收藏操作失败"
                )
            }
        }
    }
    
    fun clearError() {
        _uiState.value = _uiState.value.copy(error = null)
    }
}

data class HomeUiState(
    val recommendedRecipes: List<Recipe> = emptyList(),
    val allRecipes: List<Recipe> = emptyList(),
    val categories: List<String> = emptyList(),
    val isLoadingRecommended: Boolean = false,
    val isLoadingAll: Boolean = false,
    val isLoadingMore: Boolean = false,
    val hasMoreData: Boolean = true,
    val error: String? = null
) 